package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"ginblog/utils/validator"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

var code int

// @Produce json
// @Param username body string true "用户名"
// @Param password body string true "密码
// @Param role body int true "角色
// @Success 200 {string} "ok"
// @Failure 500 {string} "FAIL"
// @Router /api/v1/user/add [post]
// @Tags Base
// @Summary 添加用户
// @Produce  application/json
// @Param data body request.RegisterRequest true "用户注册接口"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"注册成功"}"
// @Router /base/register [POST]
func AddUser(c *gin.Context) {
	var data model.User
	var msg string
	_ = c.ShouldBindJSON(&data)
	msg, code = validator.Validate(&data)
	if code != errmsg.SUCCSE {
		c.JSON(http.StatusOK, gin.H{
			"status":  code,
			"message": msg,
		})
		return
	}
	code = model.CheckUser(data.Username)
	if code == errmsg.SUCCSE {
		model.CreateUser(&data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		code = errmsg.ERROR_USERNAME_USED
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrorMsg(code),
	})

}

// @Summary 查询用户
// @Produce json

// @Param pagesize query int false "每页显示的数量"
// @Param pagenum query int false "当前页码"
// @Success 200 {string} "ok"
// @Router /api/v1/users [get]
// 查询用户列表
func GetUserList(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))
	//if pageSize == 0 {
	//	pageSize = -1
	//}
	//if pageNum == 0 {
	//	pageNum = -1
	//}
	switch {
	case pageSize >= 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	if pageNum == 0 {
		pageNum = 1
	}
	data, total := model.GetUserList(pageSize, pageNum)
	code = errmsg.SUCCSE
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrorMsg(code),
	})
}

// @Summary 编辑用户
func UpdateUser(c *gin.Context) {
	var data model.User
	c.ShouldBindJSON(&data)
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.CheckUser(data.Username)
	if code == errmsg.SUCCSE {
		model.UpdateUser(id, &data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		c.Abort()
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrorMsg(code),
	})
}

// @Summary 删除用户
func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.DeleteUser(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrorMsg(code),
	})
}
